/**
 * wxd
 */

$(function(){
	tabEventBind();//tab页事件绑定（右击菜单、双击关闭）
	tabMenuEvenBind();//右击菜单事件绑定
	
	$("#leftMenu").accordion({ //初始化accordion
        fillSpace:true,
        fit:true,
        border:false,
        animate:false  
    });
    $.post("getMenuTreeItems.do", { id: "0" }, //获取第一层目录
       function (data) {
           if (data == "0") {
        	   $.showWarnMessage("当前用户无权限");
        	   return;
           }
           $.each(data, function (i, e) {//循环创建手风琴的项
               var id = e.id;
               $('#leftMenu').accordion('add', {
                   title: e.text,
                   content: "<ul id='tree"+id+"' ></ul>",
                   selected: true,
                   iconCls:e.icon
               });
               
               $.parser.parse();
               
               $.post("getMenuTreeItems.do?id="+id,  function(data) {//获取当前手风琴下的树
                   $("#tree" + id).tree({
                       data: data,
                       onBeforeExpand:function(node,param){  
                           $("#tree" + id).tree('options').url = "getMenuTreeItems.do?id=" + node.id;
                       },   
                       onClick : function(node){ 
                    	   if(node.url && node.url!=''){
                               var tabTitle = node.text;
                               var url = node.url;
                               var icon = node.icon;
                               addTab(tabTitle, url, icon);
                    	   }else if (node.state == 'closed'){  
                               $(this).tree('expand', node.target);  
                           }else if (node.state == 'open'){  
                               $(this).tree('collapse', node.target);  
                           }
                       }
                   });
               }, 'json');
           });
       }, "json");
});

$(function() {
	initPwdWin();
    $('#resetPassword').click(function() {
        $('#passWin').window('open');
    });
    $('#btnConfirm').click(function() {
    	resetPassword();
    })
    $('#btnCancel').click(function() { closePwdWin(); })
    $('#loginOut').click(function() {
        $.messager.confirm('系统提示', '您确定要退出本次登录吗?', function(r) {
            if (r) {
            	$.post("logout.do",function(data){
            		if(data.flag == JSON_FLAG_SUCCESS){
            			window.location.href='login.do';
            		}else{
            			$.messageBox5s('注销失败');
            		}           		
            	});           	
            }
        });
    })
});

//初始化密码设置窗口
function initPwdWin() {
    $('#passWin').window({
        title: '修改密码',
        width: 300,
        modal: true,
        shadow: true,
        closed: true,
        height: 160,
        resizable: false
    });
}

//关闭登录窗口
function closePwdWin() {
    $('#passWin').window('close');
}

//修改密码
function resetPassword() {
    var $newpass = $('#txt_NewPass');
    var $rePass = $('#txt_RePass');
    if ($newpass.val() == '') {
    	$.showWarnMessage('请输入密码！');
        return false;
    }
    if ($rePass.val() == '') {
    	$.showWarnMessage('请在一次输入密码！');
        return false;
    }
    if ($newpass.val() != $rePass.val()) {
    	$.showWarnMessage('两次密码不一至！请重新输入');
        return false;
    }
    $.post('resetPassword.do?password=' + $newpass.val(), function(data) {
    	if(data.flag == JSON_FLAG_SUCCESS){
    		$.messageBox5s('密码修改成功');
            $newpass.val('');
            $rePass.val('');
            $('#passWin').window('close');
    	}else{
    		$.messageBox5s('密码修改失败：'+data.errmsg);
    	}        
    })
}


//新增tab页
function addTab(subtitle, url, icon) {
    if (!$('#tabs').tabs('exists', subtitle)) {
        $('#tabs').tabs('add', {
            title: subtitle,
            content: createFrame(url),
            closable: true,
            icon: icon
        });
    } else {
        $('#tabs').tabs('select', subtitle);
        $('#tab_menu_refreshtab').click();
    }
    tabEventBind();
}

//创建主窗体
function createFrame(url) {
	var frameName = url.replace('.do','');
    var s = '<div style="overflow: hidden;width:100%; height:100%;" ><iframe name="'+ frameName +'" scrolling="no" frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe></div>';
    return s;
}

//为现有tab页绑定事件（双击关闭、右击菜单）
function tabEventBind() {
    /* 双击关闭TAB选项卡 */
    $(".tabs-inner").dblclick(function() {
        var subtitle = $(this).children(".tabs-closable").text();
        $('#tabs').tabs('close', subtitle);
    });
    /* 为选项卡绑定右键 */
    $(".tabs-inner").bind('contextmenu', function(e) {
        $('#tab_menu').menu('show', {
            left: e.pageX,
            top: e.pageY
        });
        //TODO  待理解
        var subtitle = $(this).children(".tabs-closable").text();
        $('#tab_menu').data("currtab", subtitle);
        $('#tabs').tabs('select', subtitle);
        return false;
    });
}

//右击菜单的各个事件绑定
function tabMenuEvenBind() {
    // 刷新
    $('#tab_menu_refreshtab').click(function() {
        var currTab = $(".tabs-panels .panel").eq($(".tabs-selected").index()).find("iframe");        
        var url = currTab.attr("src");
        currTab.attr("src", url);
    });
    //在新窗体中打开
    $("#tab_menu_opentab").click(function () {
        window.open(getCurrTab().attr("src"));
    });
    // 关闭当前
    $('#tab_menu_closetab').click(function() {
        var currtab_title = $('#tab_menu').data("currtab");
        $('#tabs').tabs('close', currtab_title);
    });
    // 全部关闭
    $('#tab_menu_closealltabs').click(function() {
        $('.tabs-inner span').each(function(i, n) {
            var t = $(n).text();
            $('#tabs').tabs('close', t);
        });
    });
    // 关闭除当前之外的TAB
    $('#tab_menu_closeothertabs').click(function() {
        $('#tab_menu_closerighttabs').click();
        $('#tab_menu_closelefttabs').click();
    });
    // 关闭当前右侧的TAB
    $('#tab_menu_closerighttabs').click(function() {
        var nextall = $('.tabs-selected').nextAll();
        if (nextall.length == 0) {
        	$.showInfoMessage('后边没有啦~~');
            return false;
        }
        nextall.each(function(i, n) {
            var t = $('a:eq(0) span', $(n)).text();
            $('#tabs').tabs('close', t);
        });
        return false;
    });
    // 关闭 当前左侧的TAB
    $('#tab_menu_closelefttabs').click(function() {
        var prevall = $('.tabs-selected').prevAll();
        if (prevall.length == 0) {
        	$.showInfoMessage('到头了，前边没有啦~~');
            return false;
        }
        prevall.each(function(i, n) {
            var t = $('a:eq(0) span', $(n)).text();
            $('#tabs').tabs('close', t);
        });
        return false;
    });
}




























//---------------------------------------（老方法）左侧导航加载 必须要双击才能打开页面的问题未解决
/*var _menus = {
	    basic: [{
	        "menuid": "10",
	        "icon": "icon-sys",
	        "menuname": "常用菜单",
	        "menus":
	                 [{
	                     "menuid": "111",
	                     "menuname": "基础数据1",
	                     "icon": "icon-nav",
	                     "url": "#"
	                 }, {
	                     "menuid": "113",
	                     "menuname": "基础数据12",
	                     "icon": "icon-nav",
	                     "url": "#"
	                 },
	        //
					  {
					  "menuid": "119",
					  "menuname": "这个是有子菜单的",
					  "icon": "icon-nav",
					  "menus": [{
					      "menuid": "120",
					      "menuname": "子菜单1",
					      "icon": "icon-nav",
					      "menus": [{
					      "menuid": "120",
					      "menuname": "子子菜单11111",
					      "icon": "icon-nav",
					      "url": "#"
					      }]
					      }]

					  },

	        //
	                 {
	                 "menuid": "115",
	                 "menuname": "基础数据13",
	                 "icon": "icon-nav",
	                 "url": "#"
	             }, {
	                 "menuid": "117",
	                 "menuname": "基础数据14",
	                 "icon": "icon-nav",
	                 "url": "#"
	             }, {
	                 "menuid": "119",
	                 "menuname": "基础数据15",
	                 "icon": "icon-nav",
	                 "url": "em/enterpriseChannelObtend.action"
	}]
	    }, {
	        "menuid": "20",
	        "icon": "icon-sys",
	        "menuname": "测试一",
	        "menus": [{
	            "menuid": "211",
	            "menuname": "测试一11",
	            "icon": "icon-nav",
	            "url": "#"
	        }, {
	            "menuid": "213",
	            "menuname": "测试一22",
	            "icon": "icon-nav",
	            "url": "#"
	}]
	}],
	            point: [{
	                "menuid": "20",
	                "icon": "icon-sys",
	                "menuname": "邮件列表",
	                "menus": [{
	                    "menuid": "211",
	                    "menuname": "邮件用途",
	                    "icon": "icon-nav",
	                    "url": "#"
	                }, {
	                    "menuid": "213",
	                    "menuname": "邮件调整",
	                    "icon": "icon-nav",
	                    "url": "#"
	}]

	}]
};

//初始化导航列表
$(function() {
	tabEventBind();//tab页事件绑定（右击菜单、双击关闭）
	tabMenuEvenBind();//右击菜单事件绑定
    $('#css3menu a').click(function() {
        $('#css3menu a').removeClass('active');
        $(this).addClass('active');
        var d = _menus[$(this).attr('name')];
        clearNav();//清空左侧导航栏
        addNav(d);//按照横向导航栏选中的菜单，加载左侧导航栏
        initLeftMenu();
    });
    // 导航菜单绑定初始化
    $("#wnav").accordion({
        animate: false
    });
    var firstMenuName = $('#css3menu a:first').attr('name');
    addNav(_menus[firstMenuName]); //首次加载basic 左侧菜单
    initLeftMenu();
});

//清空左侧导航栏
function clearNav() {
    var pp = $('#wnav').accordion('panels');
    $.each(pp, function(i, n) {
        if (n) {
            var t = n.panel('options').title;
            $('#wnav').accordion('remove', t);
        }
    });
    pp = $('#wnav').accordion('getSelected');
    if (pp) {
        var title = pp.panel('options').title;
        $('#wnav').accordion('remove', title);
    }
}

//左侧导航加载
function addNav(data) {
    $.each(data, function(i, sm) {
        var menulist1 = "";
        //sm 常用菜单  邮件 列表
        menulist1 = getMenuList(sm, menulist1);
        menulist1 = "<ul id='tt1' class='easyui-tree' animate='true' dnd='true'>" + menulist1.substring(4); 
        
        $('#wnav').accordion('add', {
            title: sm.menuname,
            content: menulist1,
            iconCls: 'icon ' + sm.icon
        });
    });
    var pp = $('#wnav').accordion('panels');
    var t = pp[0].panel('options').title;
    $('#wnav').accordion('select', t);
}

//获取导航栏的菜单列表（根据数据集合）
function getMenuList(data, menulist) {
    if (data.menus == null)
        return menulist;
    else {
        menulist += '<ul>';
        $.each(data.menus, function(i, sm) {
            if (sm.url != null) {
                menulist += '<li><a ref="' + sm.menuid + '" href="#" rel="'
					+ sm.url + '" ><span class="nav">' + sm.menuname
					+ '</span></a>'
            }
            else {
                menulist += '<li state="closed"><span class="nav">' + sm.menuname + '</span>'
            }
            menulist = getMenuList(sm, menulist);
        })
        menulist += '</ul>';
    }
    return menulist;
}

// TODO 菜单项鼠标Hover 不知道有什么用
function hoverMenuItem() {
    $(".easyui-accordion").find('a').hover(function() {
        $(this).parent().addClass("hover");
    }, function() {
        $(this).parent().removeClass("hover");
    });
}

//获取左侧导航的图标Tab
function getIcon(menuid) {
    var icon = 'icon ';
    $.each(_menus, function(i, n) {
        $.each(n, function(j, o) {
            $.each(o.menus, function(k, m) {
                if (m.menuid == menuid) {
                    icon += m.icon;
                    return false;
                }
            });
        });
    });
    return icon;
}

//初始化左侧
function initLeftMenu() {
    hoverMenuItem();
    $('#wnav li').on('click','a', function() {
        var tabTitle = $(this).children('.nav').text();
        var url = $(this).attr("rel");
        var menuid = $(this).attr("ref");
        var icon = getIcon(menuid, icon);
        addTab(tabTitle, url, icon);
        $('#wnav li div').removeClass("selected");
        $(this).parent().addClass("selected");
    });
}*/




